﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Web.Hosting;

namespace DBCore
{
    public class Config
    {
        public static XDocument ConfigDoc;
        static Config()
        {
            string path = Common.MapPath("/database.xml");
            try
            {
                ConfigDoc = XDocument.Load(path);
            }
            catch (Exception e)
            {
                try
                {
                    var url = HostingEnvironment.MapPath("~/");
                    ConfigDoc = XDocument.Load(url + "database.xml");
                }
                catch (Exception e2)
                {
                    throw (e2);
                }
            }
        }

        public static string GetValue(string path)
        {
            var elmt = ConfigDoc.XPathSelectElement(path);
            if (elmt != null)
            {
                    return elmt.Value;
            }
            else
            {
                return "";
            }
        }

        public static XElement GetXElement(string path)
        {
            return ConfigDoc.XPathSelectElement(path);
        }

        public static IEnumerable<XElement> GetXElements(string path)
        {
            return ConfigDoc.XPathSelectElements(path);
        }


        /// <summary>
        /// 得到加密后的数据库链接地址
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetDbConnectionString(string name = "default")
        {
            var elmt = GetXElements("/databases/*");

            string xAttribute = string.Empty;
            foreach (var item in elmt)
            {
                if (item.Attribute("dbname").Value == name)
                {
                    xAttribute = item.Value;
                }
            }
            return xAttribute;
        }

        #region DES 解密
        /// <summary>  
        /// 对DES加密后的字符串进行解密     
        /// </summary>     
        /// <param name="decryptoContext">待解密的字符串</param>     
        /// <param name="cryptoKey">同加密时所采用的key</param>
        /// <returns>解密后的字符串</returns>     
        public static string DesDecrypt(string decryptoContext, string cryptoKey = "utopiaLee$")
        {
            var _iv = "67^%*(&(*Ghx7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk"; //iv 向量
            //取 8 位 key
            cryptoKey = cryptoKey.PadLeft(8, '0').Substring(0, 8);
            //设置解密的 key，其值来自参数
            byte[] key = Encoding.UTF8.GetBytes(cryptoKey);
            //设置解密的 iv 向量，这里使用硬编码演示
            byte[] iv = Encoding.UTF8.GetBytes(_iv);
            //将解密正文返回到 byte 数组，加密时编码为 base64string ，这里要使用 FromBase64String 直接取回 byte 数组
            byte[] context = Convert.FromBase64String(decryptoContext);

            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Write))
                    {
                        cs.Write(context, 0, context.Length);
                        //将当前缓冲区写入绑定的内存流，然后清空缓冲区
                        cs.FlushFinalBlock();
                    }
                    //从内存流返回值，并编码到 UTF8 输出原文
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
        }
        #endregion
    }

}
